#include <iostream>
#include <vector>
#include <stdio.h>

using namespace std;

struct ListNode {
    int val;
    ListNode *next;
    ListNode() : val(0), next(nullptr) {}
    ListNode(int x) : val(x), next(nullptr) {}
    ListNode(int x, ListNode *next) : val(x), next(next) {}
};

class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        int i = 1;
        int num1 =0 ,num2=0 , num = 0, up = 0;
        
        ListNode* lnew = new ListNode();
        ListNode* node = nullptr;
        while (l1 != nullptr || l2 != nullptr || up == 1) {
            if (node == nullptr) {
                node = lnew;
            } else {
                node->next = new ListNode();
                node = node->next;
            }
            if (l1 != nullptr) {
                num1 = l1->val;
                l1 = l1->next;
            }
            else 
                num1 = 0;
            if (l2 != nullptr) {
                num2 = l2->val;
                l2 = l2->next;
            }
            else 
                num2 = 0;
            
            num = up + num1 + num2;
            if (num >= 10) {
                num = num % 10;
                up = 1;
            } else {
                up = 0;
            }
            node->val = num;
        }
        return lnew;
    }
    
};

ListNode* createLinkedList(const vector<int>& values) {
    ListNode* head = nullptr;
    ListNode* tail = nullptr;

    for (int val : values) {
        ListNode* newNode = new ListNode(val);
        if (!head) {
            head = newNode; // 第一个节点作为头
            tail = newNode; // 也是尾节点
        } else {
            tail->next = newNode; // 连接新节点
            tail = newNode;       // 更新尾节点
        }
    }
    return head;
}

void Printlist(ListNode* l)
{
    while(l != nullptr) {
        printf("%d ", l->val);
        l = l->next;
    }

}
int main()
{
    vector<int> va1 = {2,  4, 3};
    vector<int> va2 = {5,  6, 4};
    ListNode* l1 = createLinkedList(va1);
    ListNode* l2 = createLinkedList(va2);
    Solution s;
    ListNode*  r = s.addTwoNumbers(l1, l2);

    Printlist(r);
}